package com.songhaozhi.mayday.web.controller.front;


import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.songhaozhi.mayday.model.domain.User;
import com.songhaozhi.mayday.model.visitor.AlipayUser;
import com.songhaozhi.mayday.service.UserService;
import com.songhaozhi.mayday.util.JsonUtils;
import com.songhaozhi.mayday.util.RedisConstants;
import com.songhaozhi.mayday.util.RedisUtil;
import com.songhaozhi.mayday.web.controller.admin.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 支付宝第三方注册登录
 * xxd
 * 2020/04/02
 */
@Controller
@Slf4j
public class ThreeLoginController extends BaseController {

    private static final String MODEL = "/three";
    @Value("${ali.URL}")
    private String URL;
    @Value("${ali.APP_ID}")
    private String APP_ID;
    @Value("${ali.APP_PRIVATE_KEY}")
    private String APP_PRIVATE_KEY;
    @Value("${ali.FORMAT}")
    private String FORMAT;
    @Value("${ali.CHARSET}")
    private String CHARSET;
    @Value("${ali.ALIPAY_PUBLIC_KEY}")
    private String ALIPAY_PUBLIC_KEY;
    @Value("${ali.SIGN_TYPE}")
    private String SIGN_TYPE;


    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 现在改为扫码登录注册
     * @param model
     * @return
     */
    @GetMapping(MODEL + "/registerOrLogin")
    public String aliRegister(Model model) {
        // https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=商户的APPID&scope=auth_user&redirect_uri=ENCODED_URL
        String aliStr="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id="+APP_ID+"&scope=auth_user&redirect_uri="+"http%3a%2f%2fb2944625b9.zicp.vip%2fthree%2freturnAddress";
        model.addAttribute("aliStr",aliStr);
        return "ali/ali_center";
    }

    @GetMapping(MODEL + "/returnAddress")
    public String  returnAddress(@RequestParam(name = "auth_code")String authCode, @RequestParam(name = "app_id")String appId, @RequestParam(name = "scope")String scope) {
        log.info("回调成功！");
        User user=new User();
        //  auth_code获取用户的user_id和access_token
        String accessToken = getAccessToken(authCode);
        if(accessToken != null) {
            AlipayUser aUser = getUserInfoByToken(accessToken);
            log.info("AlipayUser message: {}", aUser);

            if(aUser.getUserId() == null){
                log.error("用户获取失败！");
                return "";
            }
            // 判断是否存在该账号
            User dbUser = userService.findUserById(aUser.getUserId().toString().substring(0,9));
            if(dbUser != null){
                 redisUtil.set("mayday:" + dbUser.getUserId(), JsonUtils.objectToJson(dbUser), RedisConstants.datebase0);
                 // 设置Session的过期时间
                 redisUtil.expire("mayday:" + dbUser.getUserId(), 60, RedisConstants.datebase0);//设置key过期时间
                 String msg = "redirect:/index?userId="+dbUser.getUserId().toString().substring(0,9);
                 return msg;
            }
            // 创建账号
            user.setUserId(Integer.parseInt(aUser.getUserId().substring(0,9)));
            user.setUserName(aUser.getNickName());
            user.setUserPortrait(aUser.getAvatar());
            try{
                userService.save(user);
            }catch (Exception e){
                log.error("重复注册！");
                return "redirect:/index";
            }
        }
        if(user != null){
            redisUtil.set("mayday:" + user.getUserId(), JsonUtils.objectToJson(user), RedisConstants.datebase0);
            // 设置Session的过期时间
            redisUtil.expire("mayday:" + user.getUserId(), 60, RedisConstants.datebase0);//设置key过期时间
        }
        return "redirect:/index?userId="+user.getUserId();
    }

    /**
     * 根据auth_code获取用户的user_id和access_token
     * @param authCode
     * @return
     */
    public String getAccessToken(String authCode) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            return oauthTokenResponse.getAccessToken();
        } catch (Exception e) {

            log.error("使用authCode获取信息失败！", e);
            return null;
        }
    }

    /**
     * 根据access_token获取用户信息
     * @param token
     * @return
     */
    public AlipayUser getUserInfoByToken(String token) {
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest ();
        try {
            AlipayUserInfoShareResponse response =  alipayClient.execute(request, token);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                //打印响应信息
//                System.out.println(ReflectionToStringBuilder.toString(response));
                //封装支付宝对象信息
                AlipayUser alipayUser = new AlipayUser();
                alipayUser.setAddress(response.getAddress());
                alipayUser.setCertNo(response.getCertNo());
                alipayUser.setCity(response.getCity());
                alipayUser.setCollegeName(response.getCollegeName());
                alipayUser.setDegree(response.getDegree());
                alipayUser.setMobile(response.getMobile());
                alipayUser.setPhone(response.getPhone());
                alipayUser.setProvince(response.getProvince());
                alipayUser.setUserName(response.getUserName());
                alipayUser.setNickName(response.getNickName());
                alipayUser.setUserId(response.getUserId());
                alipayUser.setAvatar(response.getAvatar());
                return alipayUser;
            }
            log.error("根据 access_token获取用户信息失败!");
            return null;

        } catch (Exception e) {
            log.error("根据 access_token获取用户信息抛出异常！", e);
            return null;
        }
    }
}


